package com.kgc.book.bookmanagerservice.service;

import com.kgc.book.bean.Bookmanage;
import com.kgc.book.bookmanagerservice.mapper.BookmanageMapper;
import com.kgc.book.service.BookService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Resource
    BookmanageMapper bookmanageMapper;
    @Resource
    JestClient jestClient;
    @Override
    public List<Bookmanage> getAll() {
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        searchSourceBuilder.query();
        Search search=new Search.Builder(searchSourceBuilder.toString()).addIndex("bookmanager").addType("book").build();
        List<Bookmanage> list=new ArrayList<>();
        try {
            SearchResult searchResult = jestClient.execute(search);
            List<SearchResult.Hit<Bookmanage, Void>> hits = searchResult.getHits(Bookmanage.class);
            for (SearchResult.Hit<Bookmanage, Void> hit : hits) {
                Bookmanage bookmanage = hit.source;
                list.add(bookmanage);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Integer deleBook(Integer id) {
        int i = bookmanageMapper.deleteByPrimaryKey(Long.parseLong(id.toString()));
        if(i>0){
            try {
                jestClient.execute(new Delete.Builder(id.toString()).index("bookmanager").type("book").build());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return i;
    }

    @Override
    public Integer addBook(Bookmanage bookmanage) {
        int insert = bookmanageMapper.insert(bookmanage);
        if(insert>0){
            Index index=new Index.Builder(bookmanage).index("bookmanager").type("book").build();
            try {
                JestResult jestResult = jestClient.execute(index);
                System.out.println(jestResult.getJsonString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return insert;
    }
}
